<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" show-icon :closable="false">
            </el-alert>
<!--            选择商品分类的级联选择器-->
            <el-row style="margin-top: 20px">
                <p>选择商品分类：
                    <el-cascader v-model="selectedOption" :options="selectedProduct" @change="handleSelectedProductChange" :props="selectedProductProps">
                    </el-cascader>
                </p>
            </el-row>
            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" :disabled="isDisabled" @click="clickAddParams">添加参数</el-button>
<!--                    动态参数表格-->
                    <el-table :data="dyParamTable" style="width: 100%" stripe border>
                        <!--展开列-->
                        <el-table-column type="expand">
                                <template slot-scope="scope">
                                    <el-tag @close="tagClose(scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i" closable :disable-transitions="false" style="margin-right: 10px">
                                        {{item}}
                                    </el-tag>
<!--                                    动态编辑标签-->
                                    <el-input v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                              class="tag_input"
                                              ref="saveTagInput"
                                              size="small"
                                              @keyup.enter.native="handleInputConfirm(scope.row)"
                                              @blur="handleInputConfirm(scope.row)">
                                    </el-input>
                                    <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>          
                                </template>
                        </el-table-column>
<!--                        索引列-->
                        <el-table-column type="index" ></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="edit(scope.row)" >编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="deleteParam(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" :disabled="isDisabled" @click="clickAddParams">添加属性</el-button>
<!--                    静态属性参数表格-->
                    <el-table :data="staticTable" style="width: 100%" stripe border>
<!--                        展开列-->
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag @close="tagClose(scope.row)" v-for="(item,i) in scope.row.attr_vals" :key="i" closable :disable-transitions="false" style="margin-right: 10px">
                                    {{item}}
                                </el-tag>
                                <!--                                    动态编辑标签-->
                                <el-input class="tag_input"
                                          v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                          ref="saveTagInput"
                                          size="small"
                                          @keyup.enter.native="handleInputConfirm(scope.row)"
                                          @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
<!--                        索引列-->
                        <el-table-column type="index" ></el-table-column>
                        <el-table-column label="属性名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" @click="edit(scope.row)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" @click="deleteParam(scope.row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
<!--        添加参数属性对话框-->
        <el-dialog :title="'添加'+titleName" :visible.sync="dialogVisible" width="30%" @close="handleCloseAddDia">
            <el-form :model="addForm"  :rules="addFormRules" ref="addFormRef" label-width="120px">
                <el-form-item :label="'添加'+titleName" prop="attr_name">
                    <el-input v-model="addForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="clickAddForm">确 定</el-button>
             </span>
        </el-dialog>
<!--        修改对话框-->
        <el-dialog :title="'修改'+titleName" :visible.sync="editDialogVisible" width="30%" @close="handleCloseEdit">
            <el-form :model="editForm"  :rules="editFormRules" ref="editFormRef" label-width="120px">
                <el-form-item :label="'修改'+titleName" prop="attr_name">
                    <el-input v-model="editForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="clickEditForm">确 定</el-button>
             </span>
        </el-dialog>

    </div>
</template>

<script>
    export default {
        name: "params",
        data(){
            return{
                //级联选择器的数据源
                selectedProduct:[],
                selectedProductProps:{
                    expandTrigger:'hover',
                    checkStrictly:true,
                    value:'cat_id',
                    label:'cat_name',
                    children:'children'
                },
                //级联选择器绑定的id
                selectedOption:[],
                activeName:'many',
                dyParamTable:[],
                staticTable:[],
                dialogVisible:false,
                editDialogVisible:false,
            //    添加参数表单
                addForm: {
                    attr_name:'',
                },
                //修改参数表单
                editForm:{
                    attr_name:'',
                    attr_id:0
                },
                addFormRules:{
                    attr_name:[
                        {required:true,message:'请输入参数名称',trigger:'blur'}
                    ]
                },
                editFormRules:{
                    attr_name:[
                        {required:true,message:'请输入参数名称',trigger:'blur'}
                    ]
                },
            }
        },
        created() {
          this.getProductCateList()
          this.getData()  
        },
        methods:{
            //获取商品分类数据
            getProductCateList(){
                this.$http.get('categories').then((res)=>{
                    if (res.data.meta.status!==200){
                        this.$message.error('获取商品分类数据失败')
                        return 
                    }
                    this.selectedProduct=res.data.data
                    
                })
            },
            //监听级联选择器绑定值发生改变
            handleSelectedProductChange(){
               this.getData()
            },
            //监听标签页发生改变
            handleClick(){
                if (this.selectedOption.length!==3){
                    return
                }
                this.getData()
            },
            //获取参数属性的数据
            getData(){
                if (this.selectedOption.length!==3){
                    return
                }
                this.$http.get('categories/'+this.selectedOption[2]+'/attributes',{params:{sel:this.activeName}}).then((res)=>{
                    if (res.data.meta.status!==200){
                        return this.$message.error('获取参数列表失败')
                    }
                    if (this.activeName==='many'){
                        res.data.data.forEach((item)=>{
                                item.inputVisible=false
                                item.inputValue=''
                                item.attr_vals==''? item.attr_vals=[]:item.attr_vals=item.attr_vals.split(' ')
                            }
                        )
                        this.dyParamTable=res.data.data
                    }else {
                        res.data.data.forEach((item)=>{
                            item.inputVisible=false
                            item.inputValue=''
                            item.attr_vals==''? item.attr_vals=[]:item.attr_vals=item.attr_vals.split(' ')
                            }
                        )
                        this.staticTable=res.data.data
                    }
                    
                })
            },
            clickAddParams(){
                this.dialogVisible=true
            },
            edit(row){
              this.editDialogVisible=true
                this.editForm.attr_name=row.attr_name
                this.editForm.attr_id=row.attr_id
            },
            //监听添加对话框关闭
            handleCloseAddDia(){
               this.$refs.addFormRef.resetFields() 
            },
            //监听编辑对话框关闭
            handleCloseEdit(){
                this.$refs.editFormRef.resetFields()
            },
            //确认添加动态参数
            clickAddForm(){
              this.$refs.addFormRef.validate(res=>{
                if (!res){
                    this.$message.error('验证不通过')
                }else {
                    this.$http.post('categories/'+this.selectedOption[2]+'/attributes',{attr_name:this.addForm.attr_name,attr_sel:this.activeName}).then((res)=>{
                        if (res.data.meta.status!==201){
                            return this.$message.error('添加参数失败')
                        }else {
                            this.$message.success('添加成功')
                            this.getData()
                            this.dialogVisible=false
                        }
                    })
                } 
              })
            },
            //确认修改参数
            clickEditForm(){
                this.$refs.editFormRef.validate(res=>{
                    if (!res){
                        this.$message.error('验证不通过')
                    }else {
                        this.$http.put('categories/'+this.selectedOption[2]+'/attributes/'+this.editForm.attr_id,{attr_name:this.editForm.attr_name,attr_sel:this.activeName}).then((res)=>{
                            if (res.data.meta.status!==200){
                                this.$message.error('修改失败')
                            }else {
                                this.$message.success('修改成功')
                                this.getData()
                                this.editDialogVisible=false
                            }
                        })
                    }
                })
            },
            //删除参数
            deleteParam(row){
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$http.delete('categories/'+this.selectedOption[2]+'/attributes/'+row.attr_id).then((res)=>{
                        this.getData()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //动态编辑标签input按下回车或者失去焦点事件
            handleInputConfirm(row){
                if (row.inputValue.trim()!==''){
                    row.attr_vals.push(row.inputValue.trim())
                    this.$http.put('categories/'+row.cat_id+'/attributes/'+row.attr_id,{attr_name:row.attr_name,attr_sel:this.activeName,attr_vals:row.attr_vals.join(' ')}).then((res)=>{
                        if(res.data.meta.status!==200){
                            this.$message.error('添加失败')
                        }else {
                            this.$message.success('添加成功')
                        }
                    })
                    row.inputValue=''
                }
                row.inputVisible=false
            },
            showInput(row){
                row.inputVisible=true
                this.$nextTick(_=>{
                    this.$refs.saveTagInput.$refs.input.focus()
                })
            },
            //监听tag关闭
            tagClose(row){
                row.attr_vals.splice(row.attr_vals.indexOf(row.inputValue),1)
                this.$http.put('categories/'+row.cat_id+'/attributes/'+row.attr_id,{attr_name:row.attr_name,attr_sel:this.activeName,attr_vals:row.attr_vals.join(' ')}).then((res)=>{
                    if(res.data.meta.status!==200){
                        this.$message.error('删除失败')
                    }else {
                        this.$message.success('删除成功')
                    }
                })

            }
        },
        computed:{
          //判断按钮是否需要禁用
          isDisabled(){
              if (this.selectedOption.length==3){
                  return false
              }else {
                  return true
              }
          }, 
            //计算title名字
           titleName(){
              if (this.activeName=='many'){
                  return '动态参数'
              }else{
                  return '静态属性'
              }
           } 
        }
    }
</script>

<style scoped>
    .tag_input{
        width: 120px;
    }
</style>
